import input from '@/utils/inputCheck';
export default {
  data() {
    return {
      captcha: '',
      captchaType: 'login',
      captchaTimeDefault: 60,
      captchaTime: 60,
      // 图形验证码token
      imgCheckToken: "",
      // 图形验证码用户输入
      imgCheckCode: "",
      // 图形验证码url
      captcha_pic: "",
      disableCaptcha: false,
      captchaTip: '发送验证码'
    };
  },
  created() {
    this.getImgCaptcha();
  },
  methods: {
    async getImgCaptcha() {
      try {
        const res = await this.$get({
          url: '/rest/V1/captcha/code/get'
        });
        this.imgCheckToken = res[0].token;
        this.captcha_pic = res[0].captcha_pic;
      } catch (e) {
        this.$$error(e.message);
      }
    },
    async setImgCaptcha({mobile = "", type = "login", token = "", code = ""}) {
      try {
        const res = await this.$post({
          url: '/rest/V1/sms/code/send/web',
          data: {
            mobile,
            type,
            token,
            code
          }
        });
        this.$$success(`验证码发送成功`);
        this.cap_timeLimit();
        return res;
      } catch (e) {
        this.$$error(e.message);
      }
    },
    async cap_send({mobile = "", type = "login"}) {
      try {
        await this.setImgCaptcha({
          mobile,
          type,
          token: this.imgCheckToken,
          code: this.imgCheckCode
        });
        // await this.$post({
        //   url: '/rest/V1/sms/code/send',
        //   data: {
        //     mobile,
        //     type
        //   }
        // });
        // await console.log(11)
      } catch (e) {
        this.$$error(e.message);
      }
    },
    cap_timeLimit() {
      if (this.captchaTime <= 0) {
        this.captchaTime = this.captchaTimeDefault;
        this.disableCaptcha = false;
        return ;
      }
      this.disableCaptcha = true;
      // 倒计时
      let interval = setInterval(() => {
        if (this.captchaTime > 0) {
            this.captchaTime = this.captchaTime - 1;
        } else {
          // 倒计时结束，重新获取信息
          clearInterval(interval);
          // 更新失效信息，再重新请求列表
          
          this.captchaTip = '重新发送';
          this.captchaTime = this.captchaTimeDefault;
          this.disableCaptcha = false;
        }
      }, 1000);
    },
    // 验证码默认phone字段，可自定义发送的手机号
    sendCaptcha(mobile = this.phone) {
      // 验证手机号
      let resPhone = input.checkPhone(mobile);
      console.log("sendCaptcha_mobile", mobile);
      if (resPhone !== -1) {
        // 如果验证不通过
        // this.$toast("xx");
        return this.$$warning(input.checkFormErrorMsg(resPhone));
      }
      
      let resImgCheck = input.checkImg(this.imgCheckCode);
      if (resImgCheck !== -1) return this.$toast(input.checkFormErrorMsg(resImgCheck));
      // 手机号验证通过
      // 点击后禁用操作
      if (this.disableCaptcha) return;
      console.log("准备发送验证码，类型是：", this.captchaType);
      this.cap_send({
        mobile,
        type: this.captchaType
      });
    },
  }
};